package sip

import (
	"fmt"
	"regexp"
	"strings"
)

type Subject struct {
	SenderID    string
	SenderSeq   string
	ReceiverID  string
	ReceiverSeq string
}

func (sub Subject) String() string {
	return fmt.Sprintf("%s:%s,%s:%s", sub.SenderID, sub.SenderSeq, sub.ReceiverID, sub.ReceiverSeq)
}

func (sub Subject) IsRealtime() bool {
	return strings.HasPrefix(sub.SenderSeq, "0")
}

func UnmarshalSubject(subStr string) (sub *Subject, err error) {
	reg := regexp.MustCompile(`(?U)^(.*):(.*),(.*):(.*)$`)
	matchs := reg.FindStringSubmatch(subStr)
	if matchs == nil {
		err = fmt.Errorf("invalid subject[%s]", subStr)
		return
	}
	sub = &Subject{
		SenderID:    matchs[1],
		SenderSeq:   matchs[2],
		ReceiverID:  matchs[3],
		ReceiverSeq: matchs[4],
	}
	return
}
